package com.wawei.seeds.me;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;

import com.wawei.seeds.R;
import com.wawei.seeds.WalnutMainActivity;
import com.wawei.seeds.adapter.SeedsBaseAdapter;
import com.wawei.seeds.model.AppModel;
import com.wawei.seeds.model.WalnutMainEvent;
import com.wawei.seeds.services.ServiceHandler;
import com.wawei.seeds.services.WalnutCheckUpdateServiceHandler;
import com.wawei.seeds.utils.ImageLoader;
import com.wawei.seeds.utils.PrefUtils;
import com.wawei.seeds.utils.RetrofitNetworkService;
import com.wawei.seeds.utils.WalnutBaseNofityHandler;

import butterknife.InjectView;
import retrofit.RestAdapter;

/**
 *
 * Created by t27891 on 15/6/22.
 */
public class MeSettingsFragment extends MeBaseFragment {
    @InjectView(R.id.item_settings_exit)View exitBtn;
    @InjectView(R.id.item_settings_password)View changePassword;
    @InjectView(R.id.item_settings_version)View checkUpdate;
    @InjectView(R.id.image_qrcode)ImageView qrCode;

    public static final int GET_QRCODE = 0x0001;
    public static final int CHECK_VERSION = 0x0002;

    private WalnutCheckUpdateServiceHandler serverHandler;
    private ServiceVersionNotifyHandler notifyHandler;
    private ImageLoader imageLoader;
    private AppModel model;

    @Override
    public View onCreateViewBeforeInjection(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_walnut_me_settings, container, false);
    }

    @Override
    public void onCreateViewAfterInjection(View view, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        serverHandler = new WalnutCheckUpdateServiceHandler(getActivity());
        notifyHandler = new ServiceVersionNotifyHandler(this);
        imageLoader = new ImageLoader(getActivity(), R.drawable.walnut_logo);
    }

    @Override
    public void onViewCreatedAfterTitle(View view, Bundle savedInstanceState) {
        exitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exitApp();
            }
        });
        changePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changePassword();
            }
        });
        checkUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //checkVersion();
                RestAdapter restAdapter = RetrofitNetworkService.makeAsyncRestAdapter();
                serverHandler.checkVersion(restAdapter, notifyHandler, CHECK_VERSION);
            }
        });

        RestAdapter restAdapter = RetrofitNetworkService.makeAsyncRestAdapter();
        serverHandler.checkVersion(restAdapter, notifyHandler, GET_QRCODE);
    }

    private void exitApp(){
        PrefUtils.markUserPassword(getActivity(), "", "");
        PrefUtils.markUserId(getActivity(), 0);

        Intent mainIntent = new Intent(getActivity(), WalnutMainActivity.class);
        mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mainIntent.putExtra(WalnutMainActivity.EXIT, true);
        getActivity().startActivity(mainIntent);
    }

    private void changePassword(){
        Intent changePasswordIntent = new Intent(getActivity(), MeSettingsChangePwdActivity.class);
        getActivity().startActivity(changePasswordIntent);
    }

    private void checkVersion() {
        Intent checkUpdateIntent = new Intent(getActivity(), MeSettingsCheckUpdateActivity.class);
        checkUpdateIntent.putExtra("url", model.getUrl());
        getActivity().startActivity(checkUpdateIntent);
    }

    @Override
    public String getTitle() {
        return getString(R.string.walnut_me_settings);
    }

    @Override
    public ServiceHandler makeServiceHandler() {
        return null;
    }

    @Override
    public SeedsBaseAdapter<WalnutMainEvent> makeListAdapter() {
        return null;
    }

    @Override
    public Bundle makeConditionBundle(int phase) {
        return null;
    }

    @Override
    public Intent makeIntent4ListItemClicked(AdapterView<?> parent, View view, int position, long id, Object itemData) {
        return null;
    }

    private class ServiceVersionNotifyHandler extends WalnutBaseNofityHandler<MeSettingsFragment, WalnutMainEvent> {

        public ServiceVersionNotifyHandler(MeSettingsFragment meSettingsFragment) {
            super(meSettingsFragment);
        }

        @Override
        public void handleOtherMessage(Message msg) {
            Bundle bundle = msg.getData();
            model = (AppModel)bundle.get(RetrofitNetworkService.RESULT_DATA);

            if (model == null) {
                Toast.makeText(get().getActivity(), "获取信息错误", Toast.LENGTH_LONG).show();
                return;
            }

            switch (msg.what) {
                case GET_QRCODE:
                    if (model.getQrCode() != null && model.getQrCode().length() > 0) {
                        get().imageLoader.loadImage(model.getQrCode(), get().qrCode, false, false);
                    } else {
                        Toast.makeText(get().getActivity(), "获取二维码失败", Toast.LENGTH_LONG).show();
                    }
                    break;
                case CHECK_VERSION:
                    try {
                        PackageManager manager = get().getActivity().getPackageManager();
                        PackageInfo info = manager.getPackageInfo(get().getActivity().getPackageName(), 0);

                        if (info.versionCode < model.getVersion()) {
                            checkVersion();
                        } else {
                            Toast.makeText(get().getActivity(), "当前版本已经是最新版本", Toast.LENGTH_LONG).show();
                        }
                    } catch (Exception e) {
                        Toast.makeText(get().getActivity(), "版本检测失败", Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    }
}
